import { constantRoutes } from '@/router'
import Layout from '@/layout'

const state = {
  routes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}

const actions = {
  generateRoutes({ commit }, data) {
    return new Promise(resolve => {
      const menuRouters = filterAsyncRouter(data)
      const Routes = constantRoutes.concat(menuRouters)
      const lastRouter = [
        // 404 page must be placed at the end !!!
        { path: '*', redirect: '/404', hidden: true }
      ]

      const newRouter = Routes.concat(lastRouter)
      commit('SET_ROUTES', newRouter)
      resolve(newRouter)
    })
  }
}

function filterAsyncRouter(route) {
  const menuRouters = []
  if (route.length > 0) {
    route.forEach(m => {
      if (!m.children || !m.children.length > 0) {
        const module = {
          path: '/' + m.path,
          name: m.name,
          component: resolve => require([`@/views/${m.path}/index`], resolve),
          hidden: m.hidden || false,
          alwaysShow: m.alwaysShow || false,
          meta: { title: m.title, icon: m.icon || '', cache: m.cache || false, buttons: m.buttons && m.buttons.length > 0 ? m.buttons : [] }
        }
        menuRouters.push(module)
      } else {
        const module = {
          path: '/' + m.path,
          name: m.name,
          component: Layout,
          redirect: m.redirect,
          hidden: m.hidden || false,
          alwaysShow: m.alwaysShow || false,
          meta: { title: m.title, icon: m.icon || '' },
          children: changeRouter(m.children, '/' + m.path)
        }
        menuRouters.push(module)
      }
    })
  }
  return menuRouters
}

function changeRouter(child, path) {
  const childRouters = []
  if (child.length > 0) {
    child.forEach(n => {
      const fullPath = path + '/' + n.path
      const module = {
        path: fullPath,
        name: n.name,
        component: resolve => require([`@/views${fullPath}`], resolve),
        redirect: n.redirect,
        hidden: n.hidden || false,
        alwaysShow: n.alwaysShow || false,
        meta: { title: n.title, activeMenu: path, cache: n.cache || false, buttons: n.buttons && n.buttons.length > 0 ? n.buttons : [] },
        children: n.children && n.children.length > 0 ? changeRouter(n.children, fullPath) : []
      }
      childRouters.push(module)
    })
  }
  return childRouters
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
